<?php
/**
 * @version : 1.0
 * @package : lib/form
 * @todo:  CURL base class. process actions on URL
*/

class CUrl {
	static $root = false;
	static $mode = 'rewrite';

	static function build_current($params=array(),$anchor='') {
	  return CUrl::build(CURL::get('page','home'),$params,$anchor);
	}

	//blacknight's edit on 2009.07.20
	static function build($page,$params=array(),$anchor='', $url_mode = '') {
		if(CUrl::$mode == 'ajax' and ($url_mode == '' or $url_mode == 'ajax') and $page) {
			$params['url_mode'] = 'ajax';
			$params['page'] = $page;
			if($page=='product_list_types') {
				if(isset($params['type'])) {
					$type = $params['type'];
					return 'javascript:if(typeof(SYS)!=\'undefined\')if(typeof(SYS.Page)!=\'undefined\'){SYS.Page.load('.str_replace('"','\'',CString($params)->json()).');SYS.Page.type = \''.$type.'\';}void(0);';
				} else {
					return 'javascript:if(typeof(SYS)!=\'undefined\')if(typeof(SYS.Page)!=\'undefined\'){SYS.Page.load('.str_replace('"','\'',CString($params)->json()).');SYS.Page.type = \'\';}void(0);';
				}
			} else
				return 'javascript:if(typeof(SYS)!=\'undefined\')if(typeof(SYS.Page)!=\'undefined\')SYS.Page.load('.str_replace('"','\'',CString($params)->json()).');void(0);';
		}
		$root_url = CPortal::$root_url;
		switch($page) {
		case 'home':
	
						return $root_url;
				break;
		case 'product_list':
			if(isset($params['category_id'])) {
				return $root_url.'danh-muc/'.$params['category_id'].'.html';
			}
			return;
		case 'empdetail':
			if(isset($params['id'])) {
			    $cache_name = 'emp_detail_'.$params['id'];
			    if(!CSystem::$cachedata->get($cache_name) or DEBUG){
			    	$product = CTable('employment')->select($params['id']);
			    	if($product){
			    		if (!empty($product['url'])) {
			    			CSystem::$cachedata->set($cache_name,CUrl::removeSign($product['url']),60*60*24);
			    		}else{
			    			CSystem::$cachedata->set($cache_name,CUrl::removeSign($product['title']),60*60*24);
			    		}
			    	}
			    };
			    $url = CSystem::$cachedata->get($cache_name);
			    return $root_url.'tuyen-dung/'.$params['id'].'_'.$url.'.html';
			}
			return;
			break;
				
		case 'fpt':
				return $root_url.'tap-doan-FPT.html';
			break;
		case 'customer':
				return $root_url.'loi-ich-khach-hang.html';
			break;
		
		case 'product_detail':
			if(isset($params['id'])) {
			    $cache_name = 'product_url'.$params['id'];
			    if(!CSystem::$cachedata->get($cache_name) or DEBUG){
			    	$product = CTable('product')->select($params['id']);
			    	if($product){
			    		if (!empty($product['product_url'])) {
			    			CSystem::$cachedata->set($cache_name,CUrl::removeSign($product['product_url']),60*60*24);
			    		}else{
			    			CSystem::$cachedata->set($cache_name,CUrl::removeSign($product['name']),60*60*24);
			    		}
			    	}
			    };
			    $url = CSystem::$cachedata->get($cache_name);
			    return $root_url.'san-pham/'.(isset($params['category_id'])?$params['category_id'].'/':'').$params['id'].'_'. $url .'.html';
			}
			return;
			break;
			
		case 'productlist':
			if(isset($params['category_id'])) {
			    return $root_url.'danh-muc/'.$params['category_id'].'.html';
			}else{
				 return $root_url.'danh-muc/mobile.html';
			}
			break;
		case 'listproduct':
				return $root_url.'san-pham-moi.html';
			break;
		case 'hotproduct':
				return $root_url.'san-pham-hot.html';
			break;
			
		case 'myphone':
				return $root_url.'my-phone.html';
			break;
		case 'myphone':
				return $root_url.'my-phone.html';
			break;
		case 'space_myphone':
				return $root_url.'my-phone/du-lieu.html';
			break;
		case 'directory_myphone':
				return $root_url.'my-phone/danh-ba.html';
			break;
			
		case 'game':
				return $root_url.'game.html';
			break;
		case 'drawing_game':
				return $root_url.'trang-tri-dien-thoai.html';
			break;
		case 'vote_game':
				return $root_url.'vote-game.html';
			break;
		
		case 'shop_gift':
				return $root_url.'shop-doi-qua.html';
			break;
		case 'shop_user_gift':
				return $root_url.'danh-sach-nhan-qua.html';
			break;
		case 'lienhe':
					return $root_url.'lien-he.html';
		case 'hotro':
					return $root_url.'ho-tro.html';
		case 'cuahang':
					return $root_url.'cua-hang.html';
		//blacknight's
		case 'product_list_types':
			if(isset($params['type']))
			{
				$type = '';
				switch($params['type'])
				{
				case 'special':
					$type = 'dac-biet';
					break;
				case 'hot':
					$type = 'hot';
					break;
				case 'new':
					$type = 'moi-ve';
					break;
				case 'comingsoon':
					$type = 'sap-ve';
					break;
				case 'saleoff':
					$type = 'giam-gia';
					break;
				}
				if(isset($params['category_id'])) {
				    return $root_url.'san-pham-dac-biet-nhat/'.$params['category_id'].'.html';
				} else
				    return $root_url.'san-pham-'.$type.'/'.$params['type'].'.html';
			}
		case 'personal':
			return $root_url.'ca-nhan.html';
		case 'search':
			if(isset($params['category_id'])) {
				 return $root_url.'search/'.$params['category_id'].'.html';
			}
			break;

		//blacknight's hotro
		case 'help':
			if(isset($params['id'])) {
			    return $root_url.'ho-tro/'.$params['id'].'_'.(isset($params['name'])? CUrl::removeSign($params['name']):'').'.html';
			}
			break;
		}

		$request_string = $root_url.((!isset($params['module']) and $page)?'?page='.$page:'?');

		if(request('_log') and user()->is_admin()) {
			$params['_log'] = request('_log');
		}

		return $request_string.CUrl::make_url($params);
	}


	static function make_url($params) {
		$request_string = '';
		if ($params) {
		  foreach ($params as $param=>$value) {
				if(is_numeric($param)) {
					  if(request($value)) {
							$request_string .= '&'.$value.'='.urlencode(request($value));
					  }
				} else {
					// Khoanb Edit 24.04.2009
					$temp_value = trim($value);
					if(!empty($temp_value)) $request_string .= '&'.$param.'='.urlencode($value);
					//$request_string .= '&'.$param.'='.urlencode($value);
				}
		  }
		}
		return $request_string;
	}

	static function redirect_current($params=array(),$anchor = '') {
		CUrl::redirect(CURL::get('page','home'),$params,$anchor);
	}

	static function redirect_href($params=false) {
		if(CUrl::check('href')) {
			  CUrl::redirect_url(CUrl::attach(request('href'),$params));
			  return true;
		}
	}

	/**
	 * Chuyen sang trang chi ra voi $url
	 *
	 * @param unknown_type $page
	 * @param unknown_type $params
	 * @param unknown_type $anchor
	 */
	static function redirect($page=false,$params=false, $anchor='') {
		if(!$page and !$params) {
			CUrl::redirect_url();
		} else {
			CUrl::redirect_url(CUrl::build($page, $params,$anchor));
		}
	}

	static function redirect_url($url=false) {
		if(!$url||$url=='') {
			$url='?'.$_SERVER['QUERY_STRING'];
		}
		header('Location:'.str_replace('&amp;','&',$url));
		CSystem::end();
	}

	static function access_denied() {
		if(CURL::get('page','home')!='home') {
			  CUrl::redirect('home');
		} else {
			  CSystem::end();
		}
	}

	static function get_num($name,$default='') {
		if (preg_match('/[^0-9.,]/',CUrl::get($name))) {
			return $default;
		} else {
			return str_replace(',','.',str_replace('.','',request($name)));
		}
	}

	static function get($name,$default='') {
		if (isset($_POST[$name])) {
			return $_POST[$name];
		} else if(isset($_GET[$name])) {
			return $_GET[$name];
		} else {
			return $default;
		}
	}

	static function sget($name,$default='') {
		return strtr(CUrl::get($name, $default),array('"'=>'\\"'));
	}

	static function jget($name,$default='')
	{
		return CString(CUrl::get($name, $default))->json();
	}

	//blacknight's 2009.07.20
	static $coDau=array('à','á','ạ','ả','ã','â','ầ','ấ','ậ','ẩ','ẫ','ă','ằ','ắ'
	    ,'ặ','ẳ','ẵ','è','é','ẹ','ẻ','ẽ','ê','ề','ế','ệ','ể','ễ','ì','í','ị','ỉ','ĩ',
	    'ò','ó','ọ','ỏ','õ','ô','ồ','ố','ộ','ổ','ỗ','ơ'
	    ,'ờ','ớ','ợ','ở','ỡ',
	    'ù','ú','ụ','ủ','ũ','ư','ừ','ứ','ự','ử','ữ',
	    'ỳ','ý','ỵ','ỷ','ỹ',
	    'đ',
	    'À','Á','Ạ','Ả','Ã','Â','Ầ','Ấ','Ậ','Ẩ','Ẫ','Ă'
	    ,'Ằ','Ắ','Ặ','Ẳ','Ẵ',
	    'È','É','Ẹ','Ẻ','Ẽ','Ê','Ề','Ế','Ệ','Ể','Ễ',
	    'Ì','Í','Ị','Ỉ','Ĩ',
	    'Ò','Ó','Ọ','Ỏ','Õ','Ô','Ồ','Ố','Ộ','Ổ','Ỗ','Ơ'
	    ,'Ờ','Ớ','Ợ','Ở','Ỡ',
	    'Ù','Ú','Ụ','Ủ','Ũ','Ư','Ừ','Ứ','Ự','Ử','Ữ',
	    'Ỳ','Ý','Ỵ','Ỷ','Ỹ',
	    'Đ','ê','ù','à');
	static $khongDau=array('a','a','a','a','a','a','a','a','a','a','a'
	    ,'a','a','a','a','a','a',
	    'e','e','e','e','e','e','e','e','e','e','e',
	    'i','i','i','i','i',
	    'o','o','o','o','o','o','o','o','o','o','o','o'
	    ,'o','o','o','o','o',
	    'u','u','u','u','u','u','u','u','u','u','u',
	    'y','y','y','y','y',
	    'd',
	    'A','A','A','A','A','A','A','A','A','A','A','A'
	    ,'A','A','A','A','A',
	    'E','E','E','E','E','E','E','E','E','E','E',
	    'I','I','I','I','I',
	    'O','O','O','O','O','O','O','O','O','O','O','O'
	    ,'O','O','O','O','O',
	    'U','U','U','U','U','U','U','U','U','U','U',
	    'Y','Y','Y','Y','Y',
	    'D','e','u','a');

	static function removeSign($str) {
		if (!isset($str)) return '';
		
		$str = str_replace(CUrl::$coDau,CUrl::$khongDau,$str);

	    $str = preg_replace('/[^a-zA-Z0-9_ -]/','',$str);
	    $str = trim($str);
	    $str = str_replace(' ','-',$str);
//	    $str = preg_replace('/[^a-zA-Z0-9_-]/','-',$str);
	    $str = str_replace(array("---", "--"), array("-", "-"), $str);

	    //o PHP, dat phia sau, sau khi chuyen ve tieng viet ko dau
	    $str = strtolower($str);
	    return $str;
	}
}

function url($page = false, $params=array(),$anchor='', $url_mode = '') {
	if(is_array($page)) {
		if(request('module')) {
			return CURL::build(false, $page+array('module'=>request('module')), is_string($params)?$params:'', $url_mode);
		} else {
			return CURL::build_current($page, is_string($params)?$params:'', '', $url_mode);
		}
	} else if($page) {
		return CURL::build($page, $params, $anchor, $url_mode);
	} else {
		return CPortal::$root_url.'?'.$_SERVER['QUERY_STRING'];
	}
}

function ajax_url($params=array(),$anchor='') {
	return url($params+array('module_id'=>module()->id), $anchor);
}

function request($name,$default = '') {
	return CUrl::get($name,$default);
}

function param($name) {
	if(request($name)) {
		return '&'.$name.'='.urlencode(request($name));
	}
}

function redirect($page = array(), $params=array(),$anchor='') {
	if(is_array($page)) {
		CURL::redirect_current($page, is_string($params)?$params:'');
	} else {
		return CURL::redirect($page, $params, $anchor);
	}
}
